<script setup lang="ts">
import { ref } from "vue";
import DeviceCategoryApi from "@/api/DeviceCategoryApi";
import { TYPE_LIST } from "../../../constants";
import { useLocalStore } from "../../../store";
import { statisticProps } from "element-plus";
import Circle from "@/views/report/device/plugins/circle";
import createCircle from "@turf/circle";
import Rectangle from "@/views/report/device/plugins/rectangle";
import Polygon from "@/views/report/device/plugins/polygon";
import { useMap } from "@/views/report/device/components/Map/index.vue";
const props = defineProps({
  statisticsCategory: Number,
  deviceCategoryList: { point: Array<any>, line: Array<any> },
});
const store = useLocalStore();
const pipelineTypeList = ref([]);
const pipePointTypeList = ref([]);
const checkAll = ref(false);
const isIndeterminate = ref(true);
const checkedPipelines = ref<any>([]);
const checkedPipePoints = ref<any>([]);
const attributeOptions = ref([]);
const valueEnumOptions = ref([]);
const valueEnumType = ref(1);
const attributeCondition = ref();
const valueEnumCondition = ref();
const isPointType = ref(false);
const jsonPolygon = ref("");
const drawType = ref(-1);
const drawManager = ref();
const getPipelineTypeList = () => {
  const params = {
    pageSize: 100,
    pageIndex: 1,
    pClassId: "02",
  };
  DeviceCategoryApi.api_query_line(params).then(({ data, succeeded }: any) => {
    if (succeeded) {
      pipelineTypeList.value = data;
    }
  });
};
const getPipePointTypeList = () => {
  const params = {
    pageSize: 100,
    pageIndex: 1,
    pClassId: "01",
  };
  DeviceCategoryApi.api_query_point(params).then(
    ({ data, succeeded }: any) => {
      if (succeeded) {
        pipePointTypeList.value = data;
      }
    }
  );
};
const handleCheckAllChange = (val: boolean) => {
  checkedPipelines.value = val ? pipelineTypeList.value.map(item => item.classId) : [];
  isIndeterminate.value = false;
};
const handleCheckedPipelinesChange = (values: string[]) => {
  const checkedCount = values.length;
  checkAll.value = checkedCount === pipelineTypeList.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < pipelineTypeList.value.length;
  // checkedPipelines.value = values;
  isPointType.value = false;
};
const onRadioChange = (value: string) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === pipelineTypeList.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < pipelineTypeList.value.length;
  checkedPipelines.value = [value];
  initialAttributeCondition(value);
  isPointType.value = value.substring(0, 2) === "01";
};
/**
 * 设置属性查询条件，填充下拉框选项
 * @param values
 */
const initialAttributeCondition = (value: string) => {
  if ([2, 3].includes(props.statisticsCategory) && value) {
    const classId = value;
    const { point, line } = props.deviceCategoryList;
    let rst = point.find((item: any) => item.classId === classId);
    if (!rst) {
      rst = line.find((item: any) => item.classId === classId);
    }
    if (rst) {
      const { classAttribute } = rst;
      // type=4 的图像字段去除
      attributeOptions.value = classAttribute
        .filter((item: any) => item.type !== 4)
        .map((item: any) => {
          return {
            label: item.attr,
            value: new Date().getTime() + Math.random(),
            data: item,
          };
        });
    }
  }
};
const getOptionsValue = (key: string, options: Array<any>) => {
  if (Array.isArray(options)) {
    const option = options.find((item) => item.value === key);
    return option?.label;
  }
  return null;
};
const draw = (type: number) => {
  clearDrawFeature();
  const map = useMap();
  switch (type) {
    case 3:
      const circle = new Circle(map);
      circle.startDraw({
        callback: (rst: any) => {
          const { lat, lng, radius } = rst;
          const options: any = { steps: 64, units: "kilometers" };
          const circle = createCircle(
            [lng, lat],
            Number(radius) / 1000,
            options
          );
          jsonPolygon.value = JSON.stringify(circle.geometry.coordinates[0]);
        },
        mouseMoveCallback: null,
      });
      drawManager.value = circle;
      break;
    case 2:
      const rect = new Rectangle(map);
      rect.startDraw({
        callback: (rst: any) => {
          const latlngs = rst.rectangle.getLatLngs();
          const points = latlngs[0].map((item: any) => [item.lng, item.lat]);
          jsonPolygon.value = JSON.stringify(points.concat([points[0]]));
        },
        mouseMoveCallback: null,
      });
      drawManager.value = rect;
      break;
    case 1:
      const polygon = new Polygon(map);
      polygon.startDraw({
        callback: (rst: any) => {
          const { points } = rst;
          let pts = points.concat([points[0]]);
          pts = pts.map((item: Array<number>) => [item[1], item[0]]);
          jsonPolygon.value = JSON.stringify(pts);
        },
        mouseMoveCallback: null,
      });
      drawManager.value = polygon;
      break;
  }
  if (drawManager.value) {
    store.setDrawManager(drawManager.value);
  }
};
const clearDrawFeature = () => {
  if (store.drawManager) {
    store.drawManager.clear();
    store.setDrawManager(null);
  }
  if (drawManager.value) {
    drawManager.value.clear();
    drawManager.value = null;
  }
};
const startStatic = () => {
  store.showStatisticChart(true);
  let attrKey, attrValue, t;
  switch (props.statisticsCategory) {
    case 0:
      attrKey = "管径";
      break;
    case 1:
      attrKey = "管材";
      break;
    case 2:
      attrKey = getOptionsValue(
        attributeCondition.value,
        attributeOptions.value
      );
      break;
    case 3:
      t = true;
      attrKey = getOptionsValue(
        attributeCondition.value,
        attributeOptions.value
      );
      attrValue = getOptionsValue(
        valueEnumCondition.value,
        valueEnumOptions.value
      );
      break;
  }
  const params: any = {
    classIds: checkedPipelines.value,
    attrKey,
    isPointType: isPointType.value,
    isStatisticsNum: !!t,
  };
  if (t) {
    params.attrValue = attrValue;
  }
  if (jsonPolygon.value) {
    params.jsonPolygon = jsonPolygon.value;
  }
  store.setStatisticsCondition(params);
};
const reset = () => {
  clearDrawFeature();
  drawType.value = -1;
  checkedPipelines.value = [];
  checkedPipePoints.value = [];
};
watchEffect(() => {
  if (props.statisticsCategory === 3 && Array.isArray(attributeOptions.value)) {
    const obj = attributeOptions.value.find(
      (item) => item.value === attributeCondition.value
    );
    if (obj) {
      const { type } = obj.data; // 1 数字 2 文本 3 选项
      if (type === 3) {
        valueEnumOptions.value = obj.data.options.map((item) => {
          return {
            label: item,
            value: new Date().getTime() + Math.random(),
          };
        });
      }
      valueEnumType.value = type;
    }
  }
});
onMounted(() => {
  clearDrawFeature();
  getPipelineTypeList();
  getPipePointTypeList();
});
onUnmounted(() => {
  reset();
})
</script>

<template>
  <div class="statisticsResult">
    <div class="header">{{ TYPE_LIST[statisticsCategory]?.name }}</div>
    <div class="pipeline">
      <el-tooltip
        class="box-item"
        effect="dark"
        content="选择绘制方式，再到地图上绘制范围"
        placement="left"
      >
        <div class="oneLevel">选择区域</div>
      </el-tooltip>
      <div class="pipelineOptions">
        <div
          :class="{ active: drawType == 1 }"
          @click="
            drawType = 1;
            draw(drawType);
          "
        >
          <span>多边形</span>
        </div>
        <div
          :class="{ active: drawType == 2 }"
          @click="
            drawType = 2;
            draw(drawType);
          "
        >
          <span>矩形</span>
        </div>
        <div
          :class="{ active: drawType == 3 }"
          @click="
            drawType = 3;
            draw(drawType);
          "
        >
          <span>圆形</span>
        </div>
      </div>
    </div>
    <div class="checkItem">
      <span class="oneLevel">选择图层</span>
      <div class="items" v-if="statisticsCategory <= 1">
        <el-checkbox
          v-if="statisticsCategory <= 1"
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
          style="margin-bottom: 10px"
        >
          全选
        </el-checkbox>
        <el-checkbox-group
          v-model="checkedPipelines"
          @change="handleCheckedPipelinesChange"
        >
          <el-checkbox
            v-for="pipeline in pipelineTypeList"
            :key="pipeline.classId"
            :label="pipeline.className"
            :value="pipeline.classId"
          >
            {{ pipeline.className }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div
        class="items"
        v-if="[2, 3].includes(statisticsCategory)"
        style="border-bottom: 1px solid rgb(128 128 128 / 10%)"
      >
        <el-radio-group
          v-model="checkedPipePoints"
          @change="onRadioChange"
          :min="0"
          :max="1"
        >
          <template v-if="statisticsCategory === 3">
            <el-radio
              v-for="pipeline in pipePointTypeList"
              :key="pipeline.classId"
              :label="pipeline.className"
              :value="pipeline.classId"
            >
              {{ pipeline.className }}
            </el-radio>
          </template>
          <el-radio
            v-for="pipeline in pipelineTypeList"
            :key="pipeline.classId"
            :label="pipeline.className"
            :value="pipeline.classId"
          >
            {{ pipeline.className }}
          </el-radio>
        </el-radio-group>
      </div>
    </div>
    <div class="moreFilter" v-if="[2, 3].includes(statisticsCategory)">
      <span class="oneLevel">更多筛选</span>
      <div class="filter">
        <span>属性：</span>
        <el-select
          v-model="attributeCondition"
          placeholder="请选择筛选条件"
          style="width: 145px"
          @change="(value) => (attributeCondition = value)"
        >
          <el-option
            v-for="item in attributeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div
        class="filter"
        v-if="statisticsCategory === 3"
        style="margin-top: 20px"
      >
        <span>数值：</span>
        <el-input-number
          v-if="valueEnumType === 1"
          v-model="valueEnumCondition"
          :min="0"
          @change="(value) => (valueEnumCondition = value)"
        />
        <el-input
          v-if="valueEnumType === 2"
          v-model="valueEnumCondition"
          style="width: 145px"
          @change="(value) => (valueEnumCondition = value)"
        />
        <el-select
          v-if="valueEnumType === 3"
          v-model="valueEnumCondition"
          placeholder="请选择筛选条件"
          style="width: 145px"
          @change="(value) => (valueEnumCondition = value)"
        >
          <el-option
            v-for="item in valueEnumOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <div class="footer">
      <el-button @click="reset">重置</el-button>
      <el-button
        type="primary"
        @click="startStatic"
        :disabled="
          statisticsCategory < 2
            ? checkedPipelines.length === 0 && checkedPipePoints.length == 0
            : !!attributeCondition === false
        "
        >开始统计</el-button
      >
    </div>
  </div>
</template>

<style scoped lang="scss">
.statisticsResult {
  position: absolute;
  top: 65px;
  right: 20px;
  z-index: 1000;
  width: 211px;
  height: 780px;
  font-family: PingFangSC-bold, sans-serif;
  color: #000;
  background-color: rgb(255 255 255 / 100%);

  .header {
    height: 40px;
    margin: 10px;
    font-size: 20px;
    font-weight: bold;
    line-height: 30px;
    color: #000;
    text-align: center;
    border-bottom: 1px solid rgb(187 187 187 / 30%);
  }

  .pipeline {
    border-bottom: 1px solid rgb(187 187 187 / 30%);

    span {
      display: inline-block;
      width: 80px;
      height: 45px;
      font-size: 14px;
      line-height: 45px;
      text-align: center;
    }

    .pipelineOptions {
      display: grid;
      grid-template-rows: 50% 50%;
      grid-template-columns: 50% 50%;
      place-items: center center;
      cursor: pointer;

      div {
        border-radius: 10px;
      }
    }

    .active {
      color: #fff;
      background: #1990ff;
      background-image: url("../../../../../../assets/images/checked.png");
      background-repeat: no-repeat;
      background-position: right bottom;
      background-size: 20px 20px;
    }
  }

  .oneLevel {
    display: inline-block;
    margin: 15px 0 10px 10px;
    font-size: 16px !important;
    font-weight: bold;
  }

  .tips {
    position: relative;
    top: -15px;
    left: -2px;
    margin: 10px 0 -5px 10px;
    font-size: 12px;
    color: red;
  }

  .split {
    width: 80%;
    height: 1px;
    margin-bottom: 5px;
    border: 1px solid rgb(128 128 128 / 10%);
  }

  .checkItem {
    border-bottom: 1px solid rgb(187 187 187 / 30%);

    span {
      display: inline-block;
      margin: 15px 0 10px 10px;
      font-size: 14px;
      font-weight: bold;
    }

    .items {
      height: 260px;
      padding-left: 30px;
      overflow-y: auto;
      cursor: pointer;

      div {
        width: 80px;
        line-height: 45px;
        text-align: center;
      }
    }
  }

  .moreFilter {
    .filter {
      padding-left: 10px;
      margin-bottom: 10px;
    }
  }

  .footer {
    position: absolute;
    bottom: 30px;
    width: auto;
    margin-top: 30px;
    margin-left: 30px;
  }
}
</style>
